<?php

namespace App\Http\Controllers\admin;

use App\Models\RoleUser;
use App\Models\User;
use App\Models\Achievement;
use App\Http\Requests\AchievementCreateRequest;
use App\Http\Requests\AchievementUpdateRequest;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\Group;
use App\Http\Controllers\Admin\BaseController;
use  App\Models\Tips;
use phpDocumentor\Reflection\Types\Null_;

class AchievementController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $caidan = $request->input('caidan',0);
        if($caidan != '1'){
            if(is_mobile()){
                $view = 'admin.achievement.achievement_manage';
            }else{
                $view = 'pc_admin.achievement.achievement_manage';
            }
            return view($view);
        }

        $now= Carbon::now();
        $year=$request->input('year',$now->year);
        $month=$request->input('month',$now->month);
        $start= Carbon::create($year,$month,1,0,0,0)->toDateTimeString();
        $end= Carbon::create($year,$month+1,0,0,0,0)->toDateTimeString();
        if($month < 10){
            $month = '0'.$month;
        }

        $uid=$this->user->id;

        if( $this->user->getRole()==9){

            $sub=user::where('corpid',$this->corpid)->where('status','1')->orderBy('is_leader','desc')->orderByRaw('CONVERT (kh_users.qw_name USING gbk)')->with(['achievement'=>function($query)use($year,$month){
                $query->where('month_param',$year.$month);
            }])->get();
            foreach ($sub as $u){
                $u->role = RoleUser::where('corpid',$this->corpid)->where('user_id',$u->id)->lists('role_id');
            }

           //dd($sub);
            $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
            $groups = $groups->toArray();
            $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
            array_unshift($groups,$groups_add);
            $tongxunlu=[];
           // $sub = $sub->toArray();
            foreach ($groups as &$g){
                $g['member'] = $this->filterUser($g['id'],$sub);
                if($g['fid'] == 0){
                    $tongxunlu[] = $g;
                }
            }
            foreach ($tongxunlu as $k=>&$t){
                if($t['id'] !=0){
                    $t['child'] = $this->filterGroup($t['id'],$groups);
                    foreach ($t['child'] as &$cld){
                        $cld['child'] = $this->filterGroup($cld['id'],$groups);
                    }
                }
            }
        }else{
            $scope=unserialize(RoleUser::where('user_id',$uid)->where("role_id",11)->first()->scope);
            if (!$scope==false){
                $sub=user::wherein('id',$scope)->where('status','1')->orderBy('is_leader','desc')->orderByRaw('CONVERT (kh_users.qw_name USING gbk)')->with(['achievement'=>function($query)use($start,$end){
                    $query->whereBetween('created_at',[$start,$end]);
                }])->get();
            }else{
                $sub=user::where('corpid',$this->corpid)->where('status','1')->orderBy('is_leader','desc')->orderByRaw('CONVERT (kh_users.qw_name USING gbk)')->with(['achievement'=>function($query)use($start,$end){
                    $query->whereBetween('created_at',[$start,$end]);
                }])->get();
            }


     //       dd($sub);
            foreach ($sub as $u){
                $u->role = RoleUser::where('corpid',$this->corpid)->where('user_id',$u->id)->lists('role_id');
            }


            $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
            $groups = $groups->toArray();
            $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
            array_unshift($groups,$groups_add);
            $tongxunlu=[];
            // $sub = $sub->toArray();
            foreach ($groups as &$g){
                $g['member'] = $this->filterUser($g['id'],$sub);
                if($g['fid'] == 0){
                    $tongxunlu[] = $g;
                }
            }
            foreach ($tongxunlu as $k=>&$t){
                if($t['id'] !=0){
                    $t['child'] = $this->filterGroup($t['id'],$groups);
                    foreach ($t['child'] as &$cld){
                        $cld['child'] = $this->filterGroup($cld['id'],$groups);
                    }
                }
            }
        }


        $tips=Tips::where("corpid",$this->corpid)->get();
      //  dd($tips);
        if(is_mobile()){
            $view = 'admin.achievement.index';
        }else{
            $view = 'pc_admin.achievement.index';
        }
        $rolearray = array('9'=>'总','10'=>'考','11'=>'业','12'=>'奖');
       // dd($tongxunlu);
        return view($view)->with('tongxunlu',$tongxunlu)->with('user',$this->user)
            ->with('year',$year)->with('month',$month)->with('start',$start)->with('roleArray',$rolearray)->with( 'tips', $tips);
    }

    private function filterUser($group_id,$users){
        $return = array();
        foreach ($users as $u){
            if($u['group_id'] == $group_id){
                $return[] = $u;
            }
        }
        return $return;
    }

    private function filterGroup($group_id,$groups){
        $return = array();
        foreach ($groups as $u){
            if($u['fid'] == $group_id){
                $return[] = $u;
            }
        }
        return $return;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(AchievementCreateRequest $request)
    {
        //
        $data=$request->FillData();
        $data['corpid']=$this->corpid;
        $data['year_param']= date('Y',strtotime($data['created_at']));
        $data['month_param']= date('Ym',strtotime($data['created_at']));

        if(!is_numeric($data['score'])){
            return  $this->formatJson('fail','创建失败，完成值为数字',$data,'/admin/init/'.$data->id.'/edit');
        }
        if(!is_numeric($data['standard']) || $data['standard'] < 0){
            return  $this->formatJson('fail','创建失败，目标为数字且>=0',$data,'/admin/init/'.$data->id.'/edit');
        }

        if ( $data["tip_id"]==0){
            $data["tip_id"]=Null;
        }
        $data=Achievement::create($data);
        return  $this->formatJson('success','创建成功',$data,'/admin/init/'.$data->id.'/edit');
    }

    /**  ay the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(AchievementUpdateRequest $request, $id)
    {
        //
        $data=$request->FillData();
        if(!is_numeric($data['score'])){
            return  $this->formatJson('fail','创建失败，完成值为数字',$data);
        }
        if(!is_numeric($data['standard']) || $data['standard'] < 0){
            return  $this->formatJson('fail','创建失败，目标为数字且>=0',$data);
        }
        $Achievement=Achievement::find($id);
        $Achievement->update($data);

        return  $this->formatJson('success','创建成功',$Achievement);
    }


    //筛选用户

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(Achievement::destroy((int)$id)){
            return  $this->formatJson('success','删除成功');
        }else{
            return  $this->formatJson('error','异常');
        }

    }

    //筛选组

    public function check(Request $request)
    {
        $tongxunlu = array();
        $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
        $groups = $groups->toArray();
        $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
        array_unshift($groups,$groups_add);

        $now= Carbon::now();
        $year=$request->input('year',$now->year);
        $month=$request->input('month',$now->month);

        if( $month==0){  //全年
            $start= Carbon::create($year,1,1,0,0,0)->toDateTimeString();
            $end= Carbon::create($year,12+1,0,23,59,59)->toDateTimeString();
            $month="全年";
        }else{
            $start= Carbon::create($year,$month,1,0,0,0)->toDateTimeString();
            $end= Carbon::create($year,$month+1,0,0,0,0)->toDateTimeString();
        }

        $users = User::where('corpid',$this->corpid)->where('status','1')->with(['achievement'=>function($query)use($start,$end){
            $query->whereBetween('created_at',[$start,$end]);
        }])->get();
        foreach ($users as $u){
            $u->role = RoleUser::where('corpid',$this->corpid)->where('user_id',$u->id)->lists('role_id');
        }
        foreach ($groups as &$g){
            $g['member'] = $this->filterUser($g['id'],$users);
            if($g['fid'] == 0){
                $tongxunlu[] = $g;
            }
        }
        foreach ($tongxunlu as $k=>&$t){
            if($t['id'] !=0){
                $t['child'] = $this->filterGroup($t['id'],$groups);
                foreach ($t['child'] as &$cld){
                    $cld['child'] = $this->filterGroup($cld['id'],$groups);
                }
            }
        }
        if(is_mobile()){
            $view = 'admin.achievement.check';
        }else{
            $view = 'pc_admin.achievement.check';
        }

        return view($view)->with('tongxunlu',$tongxunlu)->with('roleArray',$this->roleArray)->with('year',$year)->with('month',$month)->with('user',$this->user);
    }
}
